const Router = require("@koa/router")
const router = new Router()
const fileModel = require("../model/File")
const ws = require("../service/ws")
const to = require("await-to-js").default

router.post("/startEdit", async (ctx) => {
  if (ctx.empty(["fileId","userId","name"])) {
		return
	}
  const params = ctx.request.body
  const [err] = await to(
    fileModel.update(
      {
        occupyUserId: params.userId,
      },
      {
        where: {
          id: params.fileId,
        },
      }
    )
  )
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ws.broadcast(JSON.stringify({userId:params.userId,fileId:params.fileId,name:params.name,handle:"occupy"}))
  ctx.suc("操作成功")
})

router.post("/stopEdit", async (ctx) => {
  if (ctx.empty(["fileId"])) {
		return
	}
  const params = ctx.request.body
  const [err] = await  to(fileModel.update(
    {
      occupyUserId:null,
    },
    {
      where: {
        id: params.fileId,
      },
    }
  ))
  if (err) {
    ctx.err("操作失败，请重试", err)
    return
  }
  ws.broadcast(JSON.stringify({userId:params.userId,fileId:params.fileId,handle:"release"}))
  ctx.suc("操作成功")
})


module.exports = router.routes()
